package com.shunhao.utils

import android.view.View
import java.util.*

/**
 * 防止连点，仅响应设置时长的第一次操作
 *
 * @author Cuizhen
 * @date 2018/5/28-下午5:18
 */
object ClickHelper {
    var delay = 500L
    private var lastTime = 0L
    private var viewIds: MutableList<Int>? = null
    private const val SAME_VIEW_SIZE = 10

    fun onlyFirstIgnoreView(target: View?, callback: Callback) {
        val nowTime = System.currentTimeMillis()
        if (nowTime - lastTime > delay) {
            callback.onClick(target)
            lastTime = nowTime
        }
    }

    fun onlyFirstSameView(target: View, callback: Callback) {
        val nowTime = System.currentTimeMillis()
        val id = target.id
        if (viewIds == null) {
            viewIds = ArrayList(SAME_VIEW_SIZE)
        }
        if (viewIds!!.contains(id)) {
            if (nowTime - lastTime > delay) {
                callback.onClick(target)
                lastTime = nowTime
            }
        } else {
            if (viewIds!!.size >= SAME_VIEW_SIZE) {
                viewIds!!.removeAt(0)
            }
            viewIds!!.add(id)
            callback.onClick(target)
            lastTime = nowTime
        }
    }

    interface Callback {
        /**
         * 点击事件
         *
         * @param view 点击View
         */
        fun onClick(view: View?)
    }
}